<?php

/**
 * toefl API
 * Created by PhpStorm.
 * User: obelisk
 */

namespace app\modules\applets\controllers;

use yii;
use app\libs\AppControl;
use app\libs\Method;
use app\libs\Pager;
use app\modules\applets\models\Info;
use app\modules\applets\models\Banner;
use app\modules\applets\models\AppletsCollect;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

class ApiController extends AppControl
{

    public $enableCsrfValidation = false;

    function init (){
        parent::init();
        include_once($_SERVER['DOCUMENT_ROOT'].'/../libs/ucenter/ucenter.php');
    }

    /**
     * [actionHome 首页]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionHome()
    {
        $data = [];
        // banner
        $data['banner'] = Banner::find()->select(['x2_banner_applets.*','x2_info_applets.cate'])->leftJoin('x2_info_applets', 'x2_info_applets.id=x2_banner_applets.contentId')->where(['x2_banner_applets.jumpType'=>1])->orderBy('x2_banner_applets.id desc')->asArray()->all();
        // 雅思新闻
        $data['ieltsNews'] = Info::find()->where(['cate'=>1])->orderBy('id desc')->limit(3)->asArray()->all();
        // 备考攻略
        $data['beikaoRaiders'] = Info::find()->where(['cate'=>2])->orderBy('id desc')->limit(3)->asArray()->all();
        // 雅思阅读
        $data['ieltsRead'] = Info::find()->where(['cate'=>4])->orderBy('id desc')->limit(3)->asArray()->all();
        // 雅思阅读
        $data['ieltsWrite'] = Info::find()->where(['cate'=>5])->orderBy('id desc')->limit(3)->asArray()->all();
        // 雅思口语
        $data['ieltsSpeak'] = Info::find()->where(['cate'=>6])->orderBy('id desc')->limit(3)->asArray()->all();

        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionInfo 资讯集合页]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionInfo()
    {
        $data = [];
        $cate = Yii::$app->request->get('cate');
        $page = Yii::$app->request->get('page', 1);
        $pageSize = 6;
        $offset = ($page - 1) * $pageSize;
        $data = Info::find()->where(['cate'=>$cate])->orderBy('id desc')->offset($offset)->limit($pageSize)->asArray()->all();

        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionInfoDetail 资讯详情]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionInfoDetail()
    {
        $id = Yii::$app->request->get('id'); // 资讯id
        $uid = Yii::$app->request->get('uid');
        $cate = Yii::$app->request->get('cate');
        $data['detail'] = Info::find()->where(['id'=>$id])->asArray()->one();

        // 去除图片文本编辑器自带样式 并加width：100%
        $data['detail']['content'] = $this->removeImgAttr($data['detail']['content']);
        // 替换图片路径
        $data['detail']['content'] = str_replace('/files/', 'https://www.thinkuprep.com/files/', $data['detail']['content']);

        $data['detail']['createTime'] = date('Y.m.d', $data['detail']['createTime']);
        $data['detail']['isCollect'] = AppletsCollect::isCollect($id, $uid, 1);
        $data['recommand'] = Info::find()->where(['cate'=>$cate])->orderBy('id desc')->limit(3)->asArray()->all();
        Info::updateAll(['viewCount' => ($data['detail']['viewCount'] + 1)], "id=$id");
        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    private function removeImgAttr($content){
        $content = preg_replace( 
        array(
            '/(<img [^<>]*?)width=.+?[\'|\"]/',
            '/(<img.*?)((height)=[\'"]+[0-9|%]+[\'"]+)/',
            '/(<img.*?)((style)=[\'"]+(.*?)+[\'"]+)/',
        ) , array('$1 width="100%" ', '$1', '$1') , $content);
        return $content;
    }

    /**
     * [actionContentCollect 收藏、取消收藏]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionContentCollect()
    {
        $id = Yii::$app->request->get('id'); // 文章或听力id
        $uid = Yii::$app->request->get('uid');
        $option = Yii::$app->request->get('option'); // 1收藏 2取消收藏
        $type = Yii::$app->request->get('type', 1); // 1文章 2听力
        if ($option == 1) {
            $isCollect = AppletsCollect::isCollect($id, $uid, $type);
            if ($isCollect) {
                die(json_encode(['code'=>0, 'message'=>'不能重复收藏！']));
            }

            $model = new AppletsCollect();
            $model->uid = $uid;
            $model->contentId = $id;
            $model->type = $type;
            if (!$model->save()) {
                die(json_encode(['code'=>0, 'message'=>'收藏失败！']));
            }

            die(json_encode(['code'=>1, 'message'=>'收藏成功！']));
        } else {
            $res = AppletsCollect::deleteAll("uid=:uid and contentId=:contentId", array(':uid' => $uid, ':contentId'=>$id));
            if (!$res) {
                die(json_encode(['code'=>0, 'message'=>'取消收藏失败！']));
            }

            die(json_encode(['code'=>1, 'message'=>'取消收藏成功！']));
        }
    }

    /**
     * [actionBeikao 备考资料]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionBeikao()
    {
        $page = Yii::$app->request->get('page', 1);
        $pageSize = 6;
        $offset = ($page - 1) * $pageSize;
        $data = [];
        $data['activity'] = Info::find()->where(['cate'=>7])->orderBy('id desc')->offset($offset)->limit($pageSize)->asArray()->all();
        $now = time();
        if ($data['activity']) {
            foreach ($data['activity'] as $activityKey => $activityValue) {
                if (!empty($activityValue['startTime']) && !empty($activityValue['endTime'])) {
                    $data['activity'][$activityKey]['activityTime'] = date('m月d日H:i', $activityValue['startTime']) . '-' .date('H:i', $activityValue['endTime']);
                    if (($activityValue['endTime']-$activityValue['startTime']) < 86400) { // 如果是一天内的活动 不管在不在时间内，都是进行中
                        // 判断时候是否是今天
                        if (date("Y-m-d", $activityValue['startTime']) == date("Y-m-d")) {
                            $data['activity'][$activityKey]['activityStatue'] = 1; // 进行中
                        } else {
                            if ($activityValue['endTime'] < $now) {
                                $data['activity'][$activityKey]['activityStatue'] = 2; // 已结束
                            } elseif ($activityValue['startTime'] > $now) {
                                $data['activity'][$activityKey]['activityStatue'] = 0; // 未开始
                            }
                        }
                    } else {
                        if ($activityValue['endTime'] < $now) {
                            $data['activity'][$activityKey]['activityStatue'] = 2; // 已结束
                        } elseif ($activityValue['startTime'] > $now) {
                            $data['activity'][$activityKey]['activityStatue'] = 0; // 未开始
                        } else {
                            $data['activity'][$activityKey]['activityStatue'] = 1; // 进行中
                        }
                    }
                } else {
                    $data['activity'][$activityKey]['activityTime'] = '';
                    $data['activity'][$activityKey]['activityStatue'] = 0;
                }
            }
        }

        $data['ielts'] = Info::find()->where(['cate'=>8])->orderBy('id desc')->offset($offset)->limit($pageSize)->asArray()->all();

        die(json_encode(['code'=>1, 'data'=>$data]));
    }

    /**
     * [actionUcenter description]
     * @Author don
     * @Date   2022-02-17
     * @return [type]     [description]
     */
    public function actionUserCollect()
    {
        $uid = Yii::$app->request->get('uid');
        $data = AppletsCollect::find()->select(['x2_info_applets.*'])->leftJoin('x2_info_applets', 'x2_info_applets.id=x2_user_applets_collect.contentId')->where(['x2_user_applets_collect.uid'=>$uid, 'x2_user_applets_collect.type'=>1])->asArray()->all();

        die(json_encode(['code'=>1, 'data'=>$data]));
    }
}
